//
//  STOAuthViewController.swift
//  STVVeibo
//
//  Created by leergou on 16/7/20.
//  Copyright © 2016年 WhiteHouse. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class STOAuthViewController: UIViewController {
    
    override func loadView() {
        view = webView
        webView.delegate = self
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(APPREDIRECT_URI)"
        // 初始化一个 url
        let url = NSURL(string: urlString)
        
        guard let u = url else {
            return
        }
        // 初始化一个request
        let request = NSURLRequest(URL: u)
        
        webView.loadRequest(request)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    override func viewWillDisappear(animated: Bool) {
        progressView.removeProgressView()
    }
    
    //MARK: 监听方法
    @objc private func cancelClick(){
        // 关闭控制器
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFill(){
        // 自动填充
        let jsString = "document.getElementById('userId').value='\(wbAccount)',document.getElementById('passwd').value='\(wbPassword)'"
        
        // js 注入
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    //MAKR: setupUI
    func setupUI() {
        
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
        navigationController?.view.insertSubview(progressView, belowSubview: navigationController!.navigationBar)
    }

    //MARK: setupNav
    private func setupNav() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imgName: nil, target: self, action: "cancelClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", imgName: nil, target: self, action: "autoFill")
        navigationItem.title = "微博登录"
    }
    
    //MARK: - lazy
    lazy var webView: UIWebView = UIWebView()
    lazy var progressView: STOAuthProgressView = STOAuthProgressView()
    
}

extension STOAuthViewController:UIWebViewDelegate{
     func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 请求的url字符串
        let urlString = request.URL?.absoluteString
        
        if let urlStr = urlString where urlStr.hasPrefix(APPREDIRECT_URI) {
            
            let query = request.URL?.query
            if let qu = query {
                
                // 获取code
                let code = qu.substringFromIndex("code=".endIndex)
                // 获取 用户数据
//                getUserAccount(code)
                STUserAccountViewModel.sharedUserAccountTools.loadUserAccount(code, isSuccess: { (isSucc) -> () in
                    print("请求成功:\(isSucc)")
                    
                    if !isSucc{
                        print("请求失败")
                        return
                    }
                    
                    // 通知 app delegate 切换根控制器
                    // 先关闭当前页面
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        
                        // 发送一个通知 给 app delegate
                        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewContrller, object: nil)
                    })
                })
                //MAKR: - 不太理解
                return false
            }
        }
        return true
    }
    
     func webViewDidStartLoad(webView: UIWebView) {
     
//        SVProgressHUD.show()
        progressView.startAnimation()
    }
    
     func webViewDidFinishLoad(webView: UIWebView) {
//        SVProgressHUD.dismiss()
        progressView.endAnimation()
    }
    
     func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
    }
}








